﻿using System;
using System.Threading;

namespace UniRx.Operators
{
	// Token: 0x02000335 RID: 821
	internal class Wait<T> : IObserver<T>
	{
		// Token: 0x06001100 RID: 4352 RVA: 0x0004E5DC File Offset: 0x0004C9DC
		public Wait(IObservable<T> source, TimeSpan timeout)
		{
			this.source = source;
			this.timeout = timeout;
		}

		// Token: 0x06001101 RID: 4353 RVA: 0x0004E60C File Offset: 0x0004CA0C
		public T Run()
		{
			this.semaphore = new ManualResetEvent(false);
			using (this.source.Subscribe(this))
			{
				if (!((!(this.timeout == Wait<T>.InfiniteTimeSpan)) ? this.semaphore.WaitOne(this.timeout) : this.semaphore.WaitOne()))
				{
					throw new TimeoutException("OnCompleted not fired.");
				}
			}
			if (this.ex != null)
			{
				throw this.ex;
			}
			if (!this.seenValue)
			{
				throw new InvalidOperationException("No Elements.");
			}
			return this.value;
		}

		// Token: 0x06001102 RID: 4354 RVA: 0x0004E6CC File Offset: 0x0004CACC
		public void OnNext(T value)
		{
			this.seenValue = true;
			this.value = value;
		}

		// Token: 0x06001103 RID: 4355 RVA: 0x0004E6DC File Offset: 0x0004CADC
		public void OnError(Exception error)
		{
			this.ex = error;
			this.semaphore.Set();
		}

		// Token: 0x06001104 RID: 4356 RVA: 0x0004E6F1 File Offset: 0x0004CAF1
		public void OnCompleted()
		{
			this.semaphore.Set();
		}

		// Token: 0x04000A01 RID: 2561
		private static readonly TimeSpan InfiniteTimeSpan = new TimeSpan(0, 0, 0, 0, -1);

		// Token: 0x04000A02 RID: 2562
		private readonly IObservable<T> source;

		// Token: 0x04000A03 RID: 2563
		private readonly TimeSpan timeout;

		// Token: 0x04000A04 RID: 2564
		private ManualResetEvent semaphore;

		// Token: 0x04000A05 RID: 2565
		private bool seenValue;

		// Token: 0x04000A06 RID: 2566
		private T value = default(T);

		// Token: 0x04000A07 RID: 2567
		private Exception ex;
	}
}
